﻿@inject IHttpService _httpService
@inject IPopupService PopupService
@inject IUserService _userService

@inject NavigationManager NavigationManager
@inject IDataCacheService _dataCacheService
@inject IPopupService PopupService
@if (DateTime.Now.ToCstTime() > Model.BeginTime && DateTime.Now.ToCstTime() < Model.EndTime)
{
    <div style="display: flex; flex-direction: column; align-content: center;">
        @if (Model.ShowResult == false)
        {
            <MCheckbox TValue="bool" @bind-Value="IsAnonymous" Label="匿名参与投票"></MCheckbox>
            <div style=" display: flex; justify-content: center; ">
                <CnGalWebSite.Components.Buttons.MasaButton Icon="fa fa-check" Text="投票" Color="Color.Dark" IsAsync="true" OnClick="OnClickVoted"/>
            </div>
        }
        else
        {
            <div style=" display: flex; justify-content: center; ">
                <CnGalWebSite.Components.Buttons.MasaButton Icon="fa fa-refresh" Text="重新投票" Color="Color.Dark" IsAsync="true" OnClick="OnClickReVoted"/>
            </div>
        }
    </div>

}
<CnGalWebSite.Components.Verifications.DeviceIdentification @ref="deviceIdentification" />

@code {
    [Parameter]
    public VoteViewModel Model { get; set; }
    [Parameter]
    public EventCallback OnVoted { get; set; }
    [Parameter]
    public EventCallback OnReVoted { get; set; }

    public bool IsAnonymous { get; set; }
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    CnGalWebSite.Components.Verifications.DeviceIdentification deviceIdentification;


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public async Task OnClickReVoted()
    {
        await OnReVoted.InvokeAsync();
    }

    public async Task OnClickVoted()
    {
        //判断用户是否登录
        var user = await authenticationStateTask;
        if (user.User.Identity.IsAuthenticated == false)
        {
            _userService.Login();
            return;
        }
        try
        {

            var obj = await _httpService.PostAsync<UserVoteModel, Result>("api/votes/UserVote", new UserVoteModel
            {
                IsAnonymous = IsAnonymous,
                VoteId = Model.Id,
                VoteOptionIds = Model.UserSelections,
                Identification = await deviceIdentification.GetDeviceIdentificationModel()
            });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("投票失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync("投票成功", "投票成功");
                await OnVoted.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "投票失败");
        }
    }
}
